package cn.wolfcode.filter;

import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/** 局部过滤器
 *  拦截
 */
@Component
public class DayGatewayFilterFactory extends AbstractGatewayFilterFactory<DayGatewayFilterFactory.Config> {
    //构造器方法
    public DayGatewayFilterFactory(){
        super(DayGatewayFilterFactory.Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        //实际处理业务逻辑的方法
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //前置拦截
                System.out.println("前置拦截");
                System.out.println("参数值:"+config.day);
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    //后置拦截
                    System.out.println("后置拦截");
                }));
            }
        };
    }

    //反射的时候，根据字段进行值的注入
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("day");
    }

    //配置类对象，用于接收过滤器的参数
    @Setter
    @Getter
    public static class Config{
        private Integer day;
    }
}
